<?php
  if (!$_SESSION['area'] == 'lobby') {
    header('Location: index.php');
  }
  
  $db = new DbConnection();
?>

<div id="userList">
  <ul id="userListUl">
    <li class="header">Users Online</li>
    <?php
      $usrResult = $db->dbSelect("SELECT * FROM lobbyusers ORDER BY username DESC");
      if ($usrResult) {
      $userCount = 0;
        while ($lobbyUser = mysql_fetch_array($usrResult)) {
          if ($lobbyUser['loggedon'] == "1") {
            $lastActive = strtotime($lobbyUser['lastactive']);
            $allowedTime = 60 * 60 * 3; // Thats 3hrs in seconds!
            if ($lastActive > (time() - $allowedTime)) {
              echo '<li id="user'.$userCount.'">'.$lobbyUser['username'].'</li>';
              $userCount ++;
            } else {
              // Log them out!
              $db->dbUpdate("UPDATE lobbyusers SET `loggedon`='0' WHERE `username`='".$lobbyUser['username']."'");
            }
          }
        }
      }
    ?>
  </ul>
  <a href="index.php?logout=true">Logout</a>
</div>

<h3 class="welcome">Welcome to Boardwinia lobby</h3>

<div id="gamesList">
  <table id="gamesTable" cellpadding="0" cellspacing="0">
    <tr> 
      <th class="gameName">Game Name</th>
      <th>Host</th>
      <th>Players</th>
      <th>In Progress</th>
      <th>&nbsp;</th>
    </tr>
    <?php
      $gameResult = $db->dbSelect("SELECT * FROM games ORDER BY name DESC");
      if ($gameResult) {
        if (mysql_num_rows($gameResult) > 0) {
          $gamesShown = 0;
          while ($gameDetails = mysql_fetch_array($gameResult)) {
            $playersInGame = 0;
            for ($count = 1; $count < 5; $count++) {
              $column = "player". $count;
              if ($gameDetails[$column] != "-") {
                $playersInGame ++;
              }
            }
            
            if ($playersInGame == 0) {
              //delete the game
              $db->dbDelete("DELETE FROM games WHERE id='".$gameDetails['id']."'");
            } else {
              $gamesShown ++;
              echo "
              <tr>
                <td class=\"gameName\">".$gameDetails['name']."</td>
                <td>".$gameDetails['player1']."</td>
                <td>".$playersInGame . "/" . $gameDetails['maxplayers']."</td>
                <td>".displayProgress($gameDetails['inprogress'])."</td>
                <td>".displayJoinLink($gameDetails['id'])."</td>
              </tr>\n";
            }
          }
          
          if ($gamesShown == 0) {
            echo '<tr>
              <td colspan="5" class="noGames">No active games</td>
            </tr>';
          }
        } else {
          ?>
          <tr>
            <td colspan="5" class="noGames">No active games</td>
          </tr>
          <?php
        }
      }
    ?>
    
  </table>
</div>

<div id="gameOptions">
  <?php 
  $ingame = false;
  $host = false;
  if (isset($_SESSION['ingame'])) {
    $ingame = $_SESSION['ingame'];
    if (isset($_SESSION['host'])) {
      $host = $_SESSION['host'];
    }
  }
  
  debug("ingame set: ". isset($_SESSION['ingame']));
  debug("ingame:" . $ingame);
  debug("host:" . $host);
  
  if ($ingame) {
    if ($host == true) {
      ?>
      <form action="game.php" method="post">
        <input type="hidden" name="gameId" id="gameId" value="<?php echo $ingame; ?>" />
        <input type="submit" name="startGame" id="startGame" value="Start Game" disabled="disabled" />
      </form>
      <?php
    } else {
      ?>
      <form action="index.php" method="post">
        <input type="hidden" name="gameId" value="<?php echo $ingame; ?>">
        <input type="submit" name="leaveGame" value="Leave Game">
      </form>
      <?php
    }
  } else {
    ?>
    <form action="index.php" method="post"> <?php //onsubmit="return createGame()" > ?>
      <label for="gameName">Game Name:</label>
      <input id="gameName" name="gameName" value="<?php echo $_SESSION['username']; ?>'s Game">
      <label for="players">Players:</label>
      <select id="players" name="players"><option>2</option><option>3</option><option>4</option></select>
      <input type="submit" name="createGame" value="Create Game">
    </form>
    <?php
  }
  ?>
</div>

<div id="lobbyList">
  <ul id="lobbyChatUl">
    <?php
      // get the last 5 messages from the server
      $sqlResult = $db->dbSelect("SELECT * FROM lobby ORDER BY id DESC LIMIT 0, 5");
      
      if ($sqlResult) {
        $highestId = 0; $lobbyMessages = array();
        while ($sqlLobby = mysql_fetch_array($sqlResult)) {
          if ($highestId < $sqlLobby['id']) {
            $highestId = $sqlLobby['id'];
          }
          $counter = count($lobbyMessages);
          $lobbyMessages[$counter]['posted'] = $sqlLobby['posted'];
          $lobbyMessages[$counter]['username'] = $sqlLobby['username'];
          $lobbyMessages[$counter]['message'] = $sqlLobby['message'];
        }
      }
      $lobbyMessages = array_reverse($lobbyMessages);
          
      foreach ($lobbyMessages as $key => $data) {
        echo '<li><span class="postDate">('. $data['posted'] .')</span> <em class="usernameem">'. $data['username'] .'</em>: '. $data['message'] . '</li>';
        echo "\n";
      }
      
      $db->dbUpdate("UPDATE lobbyusers SET `lastreceived`='$highestId' WHERE `username`='".$username."'");
    ?>
  </ul>
</div>

<div id="userInput">
  <form action="javascript:void(0);" method="post" onsubmit="submitMessage(this)">
    <ul>
      <li class="userInput">
        <input type="hidden" name="username" id="username" value="<?php echo $username; ?>">
        <label for="msg"><?php echo $username; ?>::</label> <input type="text" name="msg" id="msg" size="40" maxlength="250" />
      </li>
      <li class="userInput"><input type="submit" name="sendMsg" value="Send" />
    </ul>
  </form>
</div>
